<template>
	<div class="base-Chart" :id="uuid"></div>
</template>
<script>
	import echarts from 'echarts'
	import uuidv1 from 'uuid/v1'

	export default {
		data() {
			return {
				myChart: {}, //生成的图表实例
				uuid: '', //唯一id
			}
		},
		props: {
			title: {
				type: String,
				default: ''
			},
			titleFontSize: {
				type: Number,
				default: 18
			},
			barWidth: {
				type: String,
				default: '40%',
			},
			barGap: {
				type: Number,
				default: 20
			},
			lineWidth: {
				type: Number,
				default: 2,
			},
			legendData: {
				type: Array,
				default(){
					return ['状态1']
				}
			},
			trigger: { //触发类型，'item'图形触发，'axis'坐标轴触发，'none'什么都不触发
				type: String,
				default: 'axis'
			},
			triggerType: { //指示器类型，'line'，'shadow'，'none'，'cross'
				type: String,
				default: 'line'
			},
			legendTop: {
				type: [Number,String],
				default: 'auto'
			},
			legendBottom: {
				type: [Number,String],
				default: 5
			},
			legendLeft: {
				type: [Number,String],
				default: 'center'
			},
			legendRight: {
				type: [Number,String],
				default: 'center'
			},
			legendWidth: {
				type: Number,
				default: 25
			},
			legendHeight: {
				type: Number,
				default: 10
			},
			legendItemGap: {
				type: Number,
				default: 25
			},
			legendIcon: {
				type: String,
				default: 'rect' //circle,rect,line,roundRect,triangle,diamond,pin,arrow,none
			},
			legendFontSize: {
				type: Number,
				default: 13
			},
			legendColor: {
				type: String,
				default: '#000'
			},


			gridTop: {
				type: Number,
				default: 45
			},
			gridBottom: {
				type: Number,
				default: 20
			},
			gridLeft: {
				type: Number,
				default: 20
			},
			gridRight: {
				type: Number,
				default: 20
			},


			
			xAxisType: { //x轴类型，'value'，'category'，'time'，'log'
				type: String,
				default: 'category'
			},
			xAxisMin: {
				type: [Boolean,String,Date],
				default() {
					return null
				}
			},
			xAxisMax: {
				type: [Boolean,String,Date],
				default() {
					return null
				}
			},
			xInterval: {
				type: [Number,Boolean],
				default() {
					return false
				}
			},
			xAxisData: {
				type: Array,
				default() {
					return []
				}
			},
			isShowXPointer: {
				type: Boolean,
				default: true
			},
			isShowXsplitLine: { //是否显示x轴分隔线
				type: Boolean,
				default: false
			},
			Xrotate: { //文字的倾斜角度
				type: Number,
				default: 45
			},
			XsplitLineInterva: { //x轴标签显示策略（隔几个）
				type: Number,
				default: 2
			},
			XsplitLineType: { //x轴分隔线类型，'dashed'，'solid'，'dotted'
				type: String,
				default: 'dashed'
			},
			isShowXaxisLine: { //是否显示x轴线
				type: Boolean,
				default: true
			},
			XaxisLabelFontSize: {
				type: Number,
				default: 10
			},
			XaxisLabelColor: {
				type: String,
				default: '#fff'
			},
			xAxisInterval: {
				type: [Number,Boolean],
				default: false
			},

			yAxisName: {
				type: String,
				default: ''
			},
			yAxisShow: {
				type: Boolean,
				default: true
			},
			yAxisType: { //y轴类型，'value'，'category'，'time'，'log'
				type: String,
				default: 'value'
			},
			yAxisData: {
				type: Array,
				default() {
					return []
				}
			},
			
			
			isShowYPointer: {
				type: Boolean,
				default: false
			},
			isShowYsplitLine: { //是否显示y轴分隔线
				type: Boolean,
				default: true
			},
			YaxisLineColor: {
				type: String,
				default: '#fff'
			},
			Yrotate: { //文字的倾斜角度
				type: Number,
				default: 0
			},
			YsplitLineInterva: { //y轴标签显示策略（隔几个）
				type: Number,
				default: 0
			},
			YsplitLineType: { //y轴分隔线类型，'dashed'，'solid'，'dotted'
				type: String,
				default: 'dashed'
			},
			isShowYaxisLine: { //是否显示Y轴线
				type: Boolean,
				default: false
			},
			YaxisLabelFontSize: {
				type: Number,
				default: 15
			},
			
			YaxisLabelColor: {
				type: String,
				default: '#fff'
			},

			yAxisName2: {
				type: String,
				default: ''
			},
			yAxisType2: { //y轴类型，'value'，'category'，'time'，'log'
				type: String,
				default: 'value'
			},
			yAxisData2: {
				type: Array,
				default() {
					return []
				}
			},
			isShowYsplitLine2: { //是否显示y轴分隔线
				type: Boolean,
				default: true
			},
			YaxisLineColor2: {
				type: String,
				default: '#fff'
			},
			Yrotate2: { //文字的倾斜角度
				type: Number,
				default: 0
			},
			YsplitLineInterva2: { //y轴标签显示策略（隔几个）
				type: Number,
				default: 0
			},
			YsplitLineType2: { //y轴分隔线类型，'dashed'，'solid'，'dotted'
				type: String,
				default: 'dashed'
			},
			isShowYaxisLine2: { //是否显示Y轴线
				type: Boolean,
				default: false
			},
			YaxisLabelFontSize2: {
				type: Number,
				default: 15
			},

			seriesDatas: {
				type: Array,
				default() {
					return []
				}
			},

			fn: {
				type: Function,
				default: null
			},
			isShowDataZoom: {
				type: Boolean,
				default: false
			}
		},
		computed: {
			isShowXAxisTick(){
				return this.isShowXaxisLine
			},
			isShowYAxisTick(){
				return this.isShowYaxisLine
			},
			isShowYAxisTick2(){
				return this.isShowYaxisLine2
			},
			isShowTitle() {
				if(this.title) {
					return true
				} else {
					return false
				}
			},
			series() {
				let seriesData = []
				let itemStyle = {}
				let lineStyle = {}
				let stack = {}
				let areaStyle = {}
				let markLine = {}
				let base = {}
				let areaStyleColor
				let yAxisIndex = {}
				let barWidth = {}
				let barGap = {}
				for(let i=0,j=this.seriesDatas.length;i<j;i++) {
					base = {
						name: this.seriesDatas[i].name,
						type: this.seriesDatas[i].type,
						data: this.seriesDatas[i].value,
						smooth: true
					}
					itemStyle = {
						itemStyle: {
							normal: {
								color: this.seriesDatas[i].color,
							}
						}
					}
					lineStyle = {
						lineStyle: {
	                        width: this.lineWidth
	                    }
					}
					if(this.seriesDatas[i].areaStyle) {
						if(this.seriesDatas[i].areaStyle.color) {
							areaStyleColor = this.seriesDatas[i].areaStyle.color
						} else {
							areaStyleColor = this.seriesDatas[i].color
						}
						areaStyle = {
							areaStyle: {
		                        color: {
								    type: 'linear',
								    x: 0,
								    y: 0,
								    x2: 0,
								    y2: 1,
								    colorStops: [{
								        offset: 0, color: areaStyleColor // 0% 处的颜色
								    }, {
								        offset: 1, color: 'rgba(255,255,255,0)' // 100% 处的颜色
								    }],
								    global: false // 缺省为 false
								}
		                    }
						}
					}
					if(this.seriesDatas[i].yAxisIndex) {
						yAxisIndex = {
							yAxisIndex: this.seriesDatas[i].yAxisIndex
						}
					}
					if(this.seriesDatas[i].barWidth) {
						barWidth = {
							barWidth: this.seriesData[i].barWidth
						}
					} else {
						barWidth = {
							barWidth: this.barWidth
						}
					}
					if(this.seriesDatas[i].barGap) {
						barGap = {
							barGap: this.seriesData[i].barGap
						}
					} else {
						barGap = {
							barGap: this.barGap
						}
					}
					if(this.seriesDatas[i].stack) {
						stack = {
							stack: this.seriesDatas[i].stack
						}
					}
					if(this.seriesDatas[i].markLine) {
						let color = ['#fff78f','#FA3934']
						if(this.seriesDatas[i].markLine.color) {
							color = this.seriesDatas[i].markLine.color
						} else {
							color = color[i]
						}
						markLine = {
							markLine: {
			                	symbol: 'none',
			                	label:{
			                		fontSize: 14,
			                		padding: [0,0,20,-80],
			                		formatter: (params) => {
			                			return params.name + ':' + params.value
			                		}
								},
			                	data: [{
									name: this.seriesDatas[i].markLine.name,
			                		lineStyle:{
		                                type:"solid",
										color: color,
										width: 2
									},
			                		yAxis: this.seriesDatas[i].markLine.value
			                	}]
							}
						}
					}
					seriesData.push(Object.assign(itemStyle,lineStyle,stack,areaStyle,markLine,barWidth,barGap,yAxisIndex,base))
				}
				return seriesData
			},
		},

		created() {
			this.uuid = uuidv1()
		},
		mounted() {
			this.initChart()
		},
		methods: {
			//格式化时间: hh:mm:ss
			formatDate(value,form) {
				form = form || "YYYY-MM-DD hh:mm:ss"
				var date = new Date(value)
				let YYYY = date.getFullYear(),
				MM = (date.getMonth() + 1) < 10 ? '0'+(date.getMonth() + 1) : (date.getMonth() + 1),
				DD = date.getDate() < 10 ? '0'+date.getDate() : date.getDate(),
				hh = date.getHours() < 10 ? '0'+date.getHours() : date.getHours(),
				mm = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes(),
				ss = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
				
				let reg1 = RegExp(/YYYY/)
				let reg2 = RegExp(/MM/)
				let reg3 = RegExp(/DD/)
				let reg4 = RegExp(/hh/)
				let reg5 = RegExp(/mm/)
				let reg6 = RegExp(/ss/)

				if(reg1.test(form)) {
					form = form.replace('YYYY',YYYY)
				}
				if(reg2.test(form)) {
					form = form.replace('MM',MM)
				}
				if(reg3.test(form)) {
					form = form.replace('DD',DD)
				}
				if(reg4.test(form)) {
					form = form.replace('hh',hh)
				}
				if(reg5.test(form)) {
					form = form.replace('mm',mm)
				}
				if(reg6.test(form)) {
					form = form.replace('ss',ss)
				}
				return form
			},
			//刷新图表
			refreshChart() {
				this.$nextTick(() => {
					this.myChart.resize()
				})
			},
			//生成条形图
			initChart() {
				this.myChart = echarts.init(document.getElementById(this.uuid))
				this.setOption()
				if(this.fn) {
					this.myChart.on('click',this.fn)
				}
			},
			setOption() {
				let dataZoom = {
					dataZoom: [
						{
							id: 'dataZoomY',
							type: 'inside',
							yAxisIndex: [0],
							filterMode: 'empty',
							start: 70,
							end: 100,
						}
		    	    ]
				}
				let title = {
					title: {
			    		show: this.isShowTitle,
			    		text: this.title,
			    		textStyle: {
			    			color: '#fff',
			    			fontSize: this.titleFontSize,
			    		},
			    		padding: [10,0,0,10]
			    	}
			    }
			    let tooltip = {
			    	tooltip: {
			    		padding: 20,
				        backgroundColor: '#222',
				        borderColor: '#777',
				        borderWidth: 1,
			    		//触发类型，'item'图形触发，'axis'坐标轴触发，'none'什么都不触发
			    		trigger: this.trigger,
			    		axisPointer: {
			    			type: this.triggerType,
			    			shadowStyle: {
			    				color: 'rgba(150,150,150,0.5)'
			    			}
			    		},
						formatter: (params) => {
			    			let legend = ''
		    				if(this.xAxisType == 'time') {
		    					legend = this.formatDate(params[0].value[0],'hh:mm') + '<br/>'
		    					for(let i=0,j=params.length;i<j;i++) {
		    						legend += `${params[i].marker}${params[i].seriesName}：${params[i].value[1]}<br/>`
		    					}
	    					} else {
	    						legend = params[0].name + '<br/>'
	    						for(let i=0,j=params.length;i<j;i++) {
	    							legend += `${params[i].marker}${params[i].seriesName}：${params[i].data}<br/>`
	    						}
	    					}
		    				

		    				return legend
			    		}
			    	}
			    }
			    let legend = {
			    	legend: {
			            data: this.legendData,
			            top: this.legendTop,
			            bottom: this.legendBottom,
			            left: this.legendLeft,
			            right: this.legendRight,
			            itemWidth: this.legendWidth,
			            itemHeight: this.legendHeight,
			            itemGap: this.legendItemGap,
			            icon: this.legendIcon,
			            textStyle: {
			            	color: this.legendColor,
			            	fontSize: this.legendFontSize,
			            },
			        }
			    }
			    let grid = {
			    	grid: {
						top: this.gridTop,
						bottom: this.gridBottom,
						left: this.gridLeft,
						right: this.gridRight,
						//grid是否包含刻度标签，更好计算
						containLabel: true,
					}
			    }
			    let xAxis = {
			    	xAxis:  {
			    		min: this.xAxisMin, //最小值
			    		max: this.xAxisMax, //最大值
			    		interval: this.xInterval, 
			            type: this.xAxisType,
			            data: this.xAxisData,
			            boundaryGap: false,
			            axisPointer: {
			                show: this.isShowXPointer
			            },
			            //分隔线
			            splitLine: {
			            	show: this.isShowXsplitLine,
			                //interval: this.XsplitLineInterva, //x轴标签显示策略（隔几个）
			                lineStyle: {
			                    color: '#74739d',
			                    type: this.XsplitLineType
			                },
			            },
			            //轴线
			            axisLine: {
			                show: this.isShowXaxisLine,
			                lineStyle: {
			                    color: '#fff',
			                }
			            },
			            //刻度线
			            axisTick: {
			                show: this.isShowXAxisTick
			            },
			            //文字
			            axisLabel: {
			            	show: true,
			            	formatter: (value, index) => {
            	                if(this.xAxisType == 'time') {
            	                	return this.formatDate(value,'hh:mm');
            	                } else {
            	                	return value
            	                }
            	            },
			            	textStyle: {
			            		color: this.XaxisLabelColor,
			            		fontSize: this.XaxisLabelFontSize,
			            	},
			            	interval: this.xAxisInterval,
			            	rotate: this.Xrotate, //倾斜文字
			            }
			        }
			    }
			    let yAxis = {
			    	yAxis: [{
			        	name: this.yAxisName,
			        	show: this.yAxisShow,
			            type: this.yAxisType,
			            data: this.yAxisData,
			            axisPointer: {
			                show: this.isShowYPointer
			            },
			            //分隔线
			            splitLine: {
			                show: this.isShowYsplitLine,
			                //interval: this.YsplitLineInterva, //y轴标签显示策略（隔几个）
			                lineStyle: {
			                    color: '#bbb',
			                    type: this.YsplitLineType
			                },
			                rotate: this.Yrotate, //倾斜文字
			            },
			            //轴线
			            axisLine: {
			            	show: this.isShowYaxisLine,
			                lineStyle: {
			                    color: this.YaxisLineColor,
			                }
			            },
			            //刻度线
			            axisTick: {
			                show: this.isShowYAxisTick
			            },
			            //文字
			            axisLabel: {
			            	show: true,
			            	textStyle: {
			            		color: this.YaxisLabelColor,
			            		fontSize: this.YaxisLabelFontSize,
			            	},
			    //         	formatter: function (value) {
							// 	return (value.length > 3 ? (value.slice(0,10) + '\n' + value.slice(11)) : value )
							// },
							interval: false,
			            },
			            //triggerEvent: true
			        },{
			        	name: this.yAxisName2,
			        	show: this.yAxisShow2,
			        	type: this.yAxisType2,
			            data: this.yAxisData2,
			            //分隔线
			            splitLine: {
			                show: this.isShowYsplitLine2,
			                //interval: this.YsplitLineInterva, //y轴标签显示策略（隔几个）
			                lineStyle: {
			                    color: '#74739d',
			                    type: this.YsplitLineType2
			                },
			                rotate: this.Yrotate2, //倾斜文字
			            },
			            //轴线
			            axisLine: {
			            	show: this.isShowYaxisLine2,
			                lineStyle: {
			                    color: this.YaxisLineColor2,
			                }
			            },
			            //刻度线
			            axisTick: {
			                show: this.isShowYAxisTick2
			            },
			            //文字
			            axisLabel: {
			            	show: true,
			            	textStyle: {
			            		fontSize: this.YaxisLabelFontSize2,
			            	},
			    //         	formatter: function (value) {
							// 	return (value.length > 3 ? (value.slice(0,10) + '\n' + value.slice(11)) : value )
							// },
							interval: false,
			            },
			            //triggerEvent: true
			        }]
			    }
			    let series = {
			    	series: this.series
			    }
				let option = {}
				if(this.isShowDataZoom) {
					Object.assign(option,dataZoom,title,tooltip,legend,grid,xAxis,yAxis,series)
				} else {
					Object.assign(option,title,tooltip,legend,grid,xAxis,yAxis,series)
				}
				
				this.myChart.setOption(option,true)
			},
			//清除实例
			disposeChart() {
				this.myChart.dispose()
			}
		},
		watch: {
			xAxisInterval: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			title: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			titleFontSize: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			barWidth: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			legendData: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			trigger: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			triggerType: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			legendBottom: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			legendFontSize: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			gridTop: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			gridBottom: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			gridLeft: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			gridRight: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			xAxisData: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			xAxisType: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			isShowXsplitLine: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			Xrotate: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			XsplitLineInterva: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			XsplitLineType: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			isShowXaxisLine: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			XaxisLabelFontSize: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			XaxisLabelColor: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			
			
			yAxisData: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			yAxisType: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			isShowYsplitLine: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			Yrotate: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			YsplitLineInterva: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			YsplitLineType: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			isShowYaxisLine: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			YaxisLabelFontSize: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			YaxisLabelColor: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			yAxisData2: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			yAxisType2: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			isShowYsplitLine2: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			Yrotate2: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			YsplitLineInterva2: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			YsplitLineType2: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			isShowYaxisLine2: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			YaxisLabelFontSize2: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			seriesDatas: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			fn: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
			stack: {
				deep: true,
				handler(newValue) {
					this.initChart()
				}
			},
		},
	}
</script>
<style>
	.base-Chart {
		width: 100%;
		height: 100%;
	}
</style>